package com.ruoyi.web.controller.jjm;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.jjm.domain.*;
import com.ruoyi.jjm.service.IAreaInfoService;
import com.ruoyi.jjm.service.ICountyStatisticsService;
import com.ruoyi.jjm.service.ITownStatisticsService;
import com.ruoyi.jjm.utils.CustomHandler;
import com.ruoyi.jjm.utils.EasyExcelUtil;
import com.ruoyi.system.domain.SysDept;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysDeptService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("/jjm/xian")
public class XianController extends BaseController {

    private String prefix = "jjm/xian";

    @Autowired
    private ITownStatisticsService townStatisticsService;

    @Autowired
    ICountyStatisticsService countyStatisticsService;

    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    IAreaInfoService areaInfoService;
    @Autowired
    private ISysDeptService deptService;


    @GetMapping(value = "/info")
    public ModelAndView info(@RequestParam(value = "xianId",required = false) Long xianId) {
        SysUser user = ShiroUtils.getSysUser();
        ModelAndView mav = new ModelAndView(prefix + "/info");
        if(xianId != null){
            mav = new ModelAndView(prefix + "/xian");
        }else {
            xianId = user.getDeptId();
        }

        mav.addObject("xianId",xianId);
        mav.addObject("xianInfo",sysDeptService.selectDeptById(xianId));
        TownStatistics chartInfo = townStatisticsService.selectTownStatisticsSum(xianId);
//        chartInfo.setCl
        Double totalAmount = townStatisticsService.sumBuyNumByCountyId(xianId);
        mav.addObject("chartInfo",chartInfo);
        mav.addObject("totalAmount",totalAmount);
        return mav;
    }
    @GetMapping(value = "/xian")
    public ModelAndView xian(@RequestParam(value = "xianId",required = false) Long xianId) {
        SysUser user = ShiroUtils.getSysUser();
        ModelAndView mav = new ModelAndView(prefix + "/xian");
        if(xianId != null){
            mav.addObject("xianId",xianId);
        } else {
            xianId = user.getDeptId();
        }
        mav.addObject("xianInfo",sysDeptService.selectDeptById(xianId));
        TownStatistics chartInfo = townStatisticsService.selectTownStatisticsSum(xianId);
//        chartInfo.setCl
        Double totalAmount = townStatisticsService.sumBuyNumByCountyId(xianId);
        mav.addObject("chartInfo",chartInfo);
        mav.addObject("totalAmount",totalAmount);
        return mav;
    }


    @GetMapping(value = "/mobile")
    public ModelAndView mobile(@RequestParam(value = "id") Long xianId) {
        SysUser user = ShiroUtils.getSysUser();
        ModelAndView mav = new ModelAndView(prefix + "/xianMobile");
        mav.addObject("xianId",xianId);
        mav.addObject("xianInfo",sysDeptService.selectDeptById(xianId));
        Double totalAmount = townStatisticsService.sumBuyNumByCountyId(xianId);
        mav.addObject("totalAmount",totalAmount);

        List<SysDept> deptList = deptService.selectDeptByParentId(xianId);
        mav.addObject("deptList",deptList);
        return mav;
    }

    @PostMapping("/tableInfo")
    @ResponseBody
    public TableDataInfo infoTable(@RequestParam(value = "xianId",required = false) Long xianId) {
        SysUser user = ShiroUtils.getSysUser();
        startPage();
        if(xianId == null){
            xianId = user.getDeptId();
        }
        CountyStatistics countyStatistics = reportData(xianId);

        SysDept xianInfo = deptService.selectDeptById(xianId);
        countyStatistics.setId(1L);
        countyStatistics.setCountyName(xianInfo.getDeptName());
        List<CountyStatistics> tableList = Arrays.asList(countyStatistics);
        return getDataTable(tableList);
    }
    @PostMapping("/xianInfo")
    @ResponseBody
    public TableDataInfo xianInfo(@RequestParam(value = "xianId",required = false) Long xianId) {
        SysUser user = ShiroUtils.getSysUser();
        startPage();
        TownStatistics query = new TownStatistics();
        if(xianId == null){
            xianId = user.getDeptId();
        }
        query.setCountyId(xianId);
        List<TownStatistics> tableList = townStatisticsService.selectTownStatisticsList(query);
        return getDataTable(tableList);
    }

    private CountyStatistics reportData(Long xianId){
        SysUser user = ShiroUtils.getSysUser();
        CountyStatistics countyStatistics = townStatisticsService.selectSumStatisticsByXianId(xianId);
        countyStatistics.setUpdateBy(user.getLoginName());
        AreaInfo countyInfo = areaInfoService.selectAreaInfoByAreaId(countyStatistics.getCountyId());
        if(countyInfo != null){
            countyStatistics.setCountyBlNum(countyInfo.getBaolianCadreNum());
            countyStatistics.setCountyBlTownNum(countyInfo.getBaolianAreaNum());
        }
        return countyStatistics;
    }

    @GetMapping("/reportData")
    @ResponseBody
    public AjaxResult reportData() {
        SysUser user = ShiroUtils.getSysUser();
        if(user.getDept().getAncestors().split(",").length == 2){
            Long xianId = user.getDeptId();
            CountyStatistics countyStatistics = reportData(xianId);
            countyStatisticsService.insertOrUpdateByXianId(countyStatistics);
        }
        return AjaxResult.success("ok");
    }

    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(@RequestParam(value = "countyId",required = false) Long countyId) throws InvocationTargetException, IllegalAccessException {
        SysUser user = ShiroUtils.getSysUser();
        if(countyId == null){
            countyId = user.getDeptId();
        }
        SysDept dept = deptService.selectDeptById(countyId);
        CountyStatistics query = new CountyStatistics();
        query.setCountyId(countyId);
        List<CountyStatistics> list = countyStatisticsService.selectCountyStatisticsList(query);
        if(CollectionUtils.isEmpty(list)){
            return AjaxResult.warn("居民户籍信息为空");
        }
        List<CountyStatisticsTable> tableList = new ArrayList<>();
        for(CountyStatistics statistics : list){
            CountyStatisticsTable table = new CountyStatisticsTable();
            BeanUtils.copyProperties(table,statistics);
            tableList.add(table);
        }
        String fileName = dept.getDeptName()+"居民户籍信息" + System.currentTimeMillis() + ".xlsx";

        EasyExcel.write(Global.getDownloadPath()+fileName, CountyStatisticsTable.class)
                .needHead(true)
                .head(CountyStatisticsTable.class)
                .excelType(ExcelTypeEnum.XLSX)
                .registerWriteHandler(new CustomHandler())
                .registerWriteHandler(EasyExcelUtil.getStyleStrategy()).sheet("居民户籍信息").doWrite(tableList);
        return AjaxResult.success(fileName);
    }
    @PostMapping("/exportXian")
    @ResponseBody
    public AjaxResult exportXian(@RequestParam(value = "countyId",required = false) Long countyId) throws InvocationTargetException, IllegalAccessException {
        SysUser user = ShiroUtils.getSysUser();
        SysDept dept = user.getDept();
        if(countyId == null){
            countyId = dept.getDeptId();
        }
        dept = deptService.selectDeptById(countyId);
        TownStatistics query = new TownStatistics();
        query.setCountyId(countyId);
        List<TownStatistics> list = townStatisticsService.selectTownStatisticsList(query);
        if(CollectionUtils.isEmpty(list)){
            return AjaxResult.warn("居民户籍信息为空");
        }
        List<TownStatisticsTable> tableList = new ArrayList<>();
        for(TownStatistics statistics : list){
            TownStatisticsTable table = new TownStatisticsTable(statistics);
            tableList.add(table);
        }
        String fileName = dept.getDeptName()+"居民户籍信息" + System.currentTimeMillis() + ".xlsx";

        EasyExcel.write(Global.getDownloadPath()+fileName, TownStatisticsTable.class)
                .needHead(true)
                .head(TownStatisticsTable.class)
                .excelType(ExcelTypeEnum.XLSX)
                .registerWriteHandler(new CustomHandler())
                .registerWriteHandler(EasyExcelUtil.getStyleStrategy()).sheet("居民户籍信息").doWrite(tableList);
        return AjaxResult.success(fileName);
    }
}
